var http = require('http'); 
var fs = require('fs'); 
const phantom = require('phantom'); 
module.exports =  {
	/**
	 * 获取url内容
	 * @param {*目标url} url 
	 */
	asyncHttp(url) {
		return new Promise(function (resolve, reject) {
			http.get(url, function(res) {
				var data = ''; 
				res.on('data', function(chunk) {
					data += chunk; 
				}); 
				res.on('end', function() {
					resolve(data); 
				})
			})
		})
	}, 
	/**
	 * 写入文件数据
	 * @param {*数据} dataObj 
	 * @param {*文件路径} filePath 
	 */
	writeData(dataObj, filePath) {
	 	return new Promise(function (resolve, reject) {
			var w_data = new Buffer(JSON.stringify(dataObj)); 
			fs.writeFile(filePath, w_data,  {flag:'w', encoding:'utf8'}, function(err) {
				if (err) {
					console.log(err); 
					reject()
					return; 
				}
				resolve(); 
				
			})		
	 	})
		
	},
	// 异步阻塞
	sleep (time) {
	    return new Promise(function (resolve, reject) {
	        setTimeout(function () {
	            resolve("等" + time + "毫秒"); 
	        }, time); 
	    })
	},
	/**
	 * 判断文件是否存在
	 * @param {*文件路径} filePath 
	 */
	fileExits(filePath) {
		return new Promise(function (resolve, reject) {
				 fs.exists(filePath, function (exists) {
        		 console.log(filePath); 
		 		var fileExists = exists?true:false; 
				resolve(fileExists); 
			}); 
		})
	},
    /*
		参数:
		DownLoadPageURL: 要渲染的页面
		website: 页面来源 dm5,dmzz等
    */
	getImageURL(DownLoadPageURL, website) {
		return new Promise(function (resolve, reject) {
			console.log(DownLoadPageURL); 
			( function () {
			const instance =  phantom.create();
		    instance.then(function(instance){
				page = instance.createPage()
				page.then(function(page){
					page.on("onResourceRequested", function(requestData) {
						var url = requestData.url; 
						if (website == "dm5") {
							if (url.indexOf('cid') != -1 && url.indexOf("key") != -1 && (url.indexOf('png') != -1 || url.indexOf('jpg') != -1)) {
									resolve(url); 
								}	
							}
						}); 
						const status = page.open(DownLoadPageURL); 
				}) 
			});
		}()); 
		})
	},
	/**
	 * 创建文件
	 * @param {*目标文件路径} folderPath 
	 */
	createDir(folderPath) {
		//判断该目录是否已经存在,如果已经存在则不再创建,如果不存在则创建
		return new Promise(function(resolve,reject){
			fs.exists(folderPath, function(exists) {
				if (exists) {
					console.log("该目录已存在" + folderPath); 
					resolve(true)
				}else {
					fs.mkdir(folderPath, function(err) {
						if (err) {
							console.log("目录创建失败"); 
							console.log(err); 
							reject(false)
							return; 
						}else {
							resolve(true)
							// console.log("目录创建成功");
						}
					})
				}
			})
		})
	},
	
	/**
	 * 过滤字符串
	 * @param {*} str 
	 */
	filterString(str){
		var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
        var rs = "";
    	for (var i = 0; i < str.length; i++) {
        	rs = rs + str.substr(i, 1).replace(pattern, '');
    	}
    return rs;
	}
}

